package com.myMinistry.gui;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import com.myMinistry.R;
import com.myMinistry.provider.MinistryContract.Publisher;
import com.myMinistry.provider.MinistryService;

public class PublisherEditor extends FragmentActivity {
	private CheckBox isActive;
	private EditText name;
	private MinistryService database;
	private int publisherID = 0;
	
	@Override
	public void onStart() {
		super.onStart();
		if(publisherID > 0) {
			database.openReadable();
			Cursor record = database.fetchPublisher(publisherID);
			if(record.moveToFirst()) {
				name.setText(record.getString(record.getColumnIndex(Publisher.NAME)));
				if(record.getInt(record.getColumnIndex(Publisher.ACTIVE)) == MinistryService.ACTIVE)
					isActive.setChecked(true);
			}
			record.close();
			database.close();
		}
	}
    
    @Override
	public void onStop() {
    	super.onStop();
    	database.close();
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        	startActivity(new Intent(getApplicationContext(), Publishers.class));
			finish();
        }
        return super.onKeyDown(keyCode, event);
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Bundle extras = getIntent().getExtras();
    	setContentView(R.layout.publisher_editor);
    	
    	if(extras != null) {
	    	Object[] keys = extras.keySet().toArray();
	    	for(int i = 0; i < keys.length; i++) {
	    		if(keys[i].toString().equals("publisherID"))
	    			publisherID = extras.getInt("publisherID");
	    	}
	    }
    	
    	database = new MinistryService(this);
    	
    	name = (EditText)findViewById(R.id.name);
    	isActive = (CheckBox)findViewById(R.id.isActive);
    	
    	findViewById(R.id.saveButton).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				save();
			}
		});
    }
	
	public void updatePublisher(int newPublisherID, String publisherName) {
		/** Update display name from fragment */
		ActionBarFragment fragment = (ActionBarFragment)getSupportFragmentManager().findFragmentById(R.id.action_bar_fragment);
		fragment.setSelectedPublisherNameText(publisherName);
	}
	
	public void showDialog() {
		/** DialogFragment.show() will take care of adding the fragment
		 * in a transaction. We also want to remove any currently showing
		 * dialogs, so make our own transaction and take care of that here. */
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if(prev != null)
			ft.remove(prev);
		ft.addToBackStack(null);
		/** Create and show the dialog. */
		DialogFrag newFragment = DialogFrag.newInstance(getApplicationContext().getString(R.string.menuPublishers), DialogFrag.ACTIVE_PUBLISHERS);
		newFragment.show(getSupportFragmentManager(), "dialog");
	}
	
	public void createNewPublisherShowDialog() {
		/** DialogFragment.show() will take care of adding the fragment
		 * in a transaction. We also want to remove any currently showing
		 * dialogs, so make our own transaction and take care of that here. */
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if(prev != null)
			ft.remove(prev);
		ft.addToBackStack(null);
		/** Create and show the dialog. */
		DialogFrag newFragment = DialogFrag.newInstance(getApplicationContext().getString(R.string.publishersName), DialogFrag.CREATE_PUBLISHER);
		newFragment.show(getSupportFragmentManager(), "dialog");
	}
	
	public void save() {
		ContentValues values = new ContentValues();
		values.put(Publisher.NAME, name.getText().toString());
		values.put(Publisher.ACTIVE, (isActive.isChecked()) ? MinistryService.ACTIVE : MinistryService.INACTIVE);
		database.openWritable();
		if(publisherID > 0)
			database.updatePublisher(publisherID, values);
		else
			database.createPublisher(values);
		database.close();
    	startActivity(new Intent(getApplicationContext(), Publishers.class));
		finish();
	}
}